package service

import (
	"cms/core"
	"cms/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"github.com/wdaglb/korm"
)

// GetCurrentAdmin 获取当前登陆管理员信息
func GetCurrentAdmin(ctx *gin.Context) *model.Admin {
	val, ok := ctx.Get("admin_user")
	if !ok {
		return nil
	}
	user := val.(string)
	if exData, ok := ctx.Get("current_admin"); ok {
		switch exData.(type) {
		case *model.Admin:
			return exData.(*model.Admin)
		}
	}

	data := &model.Admin{}
	db := korm.NewContext()
	res := db.Model(&data).Where("Username", user).Find()
	if res.Error != nil {
		logrus.Errorf("get admin user: %v", res.Error)
		return nil
	}
	if !res.Exist {
		logrus.Warnf("admin check_login username[%s] not exist", user)
		return nil
	}
	ctx.Set("current_admin", data)

	return data
}

// HasPermission 用户是否拥有权限
func HasPermission(username string, permission string, method string) bool {
	enforce, err := core.Enforcer.Enforce(username, permission, method)
	if err != nil {
		return false
	}

	return enforce
}

// Enforce 确定用户是否有权限
func Enforce(vars ...interface{}) bool {
	enforce, err := core.Enforcer.Enforce(vars...)
	if err != nil {
		return false
	}

	return enforce
}

// HasRoleForUser 用户是否拥有用户组
func HasRoleForUser(username string, groupId int) bool {
	ok, err := core.Enforcer.HasRoleForUser(username, fmt.Sprintf("group:%d", groupId))
	if err != nil {
		return false
	}
	return ok
}

// GetAdminGroup 获取管理所属的用户组
func GetAdminGroup(username string) []model.AdminGroup {
	str, _ := core.Enforcer.GetRolesForUser(username)
	list := make([]model.AdminGroup, 0)
	ctx := korm.NewContext()
	ctx.Model(&list).Where("Id", "in", str).Select()
	return list
}

// GetAdminPermissions 获取管理拥有的权限
func GetAdminPermissions(username string) [][]string {
	user, err := core.Enforcer.GetImplicitPermissionsForUser(username)
	if err != nil {
		return [][]string{}
	}
	if user == nil {
		return [][]string{}
	}

	return user
}

// GetGroupUsers 获取用户组的用户
func GetGroupUsers(groupId int) []string {
	users, err := core.Enforcer.GetUsersForRole(fmt.Sprintf("group:%d", groupId))
	if err != nil {
		return []string{}
	}
	return users
}

// AddGroupPermission 给用户组添加权限
func AddGroupPermission(groupId int, permissions ...string) error {
	_, err := core.Enforcer.AddPermissionForUser(fmt.Sprintf("group:%d", groupId), permissions...)
	return err
}

// DeleteGroupPermission 为用户组删除权限
func DeleteGroupPermission(groupId int, permissions ...string) error {
	_, err := core.Enforcer.DeletePermissionForUser(fmt.Sprintf("group:%d", groupId), permissions...)
	return err
}

// AddUserPermission 给用户添加权限
func AddUserPermission(userId int, permissions ...string) error {
	_, err := core.Enforcer.AddPermissionForUser(fmt.Sprintf("%d", userId), permissions...)
	return err
}

// DeleteUserPermission 为用户组删除权限
func DeleteUserPermission(groupId int, permissions ...string) error {
	_, err := core.Enforcer.DeletePermissionForUser(fmt.Sprintf("%d", groupId), permissions...)
	return err
}

// AddGroupUsers 为用户组绑定用户
func AddGroupUsers(groupId int, username ...string) error {
	for _, user := range username {
		_, err := core.Enforcer.AddRolesForUser(user, []string{fmt.Sprintf("%d", groupId)})
		if err != nil {
			return err
		}
	}

	return nil
}

// DeleteGroupUser 删除用户组的部分用户
func DeleteGroupUser(groupId int, username ...string) error {
	for _, user := range username {
		_, err := core.Enforcer.DeleteRoleForUser(user, fmt.Sprintf("%d", groupId))
		if err != nil {
			return err
		}
	}

	return nil
}

// DeleteGroup 删除用户组
func DeleteGroup(groupId int) error {
	_, err := core.Enforcer.DeleteRole(fmt.Sprintf("%d", groupId))
	if err != nil {
		return err
	}

	return nil
}
